package com.fragrance.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.aliyun.iot.client.IotClient;
import com.aliyuncs.iot.model.v20170420.QueryDeviceByNameResponse.DeviceInfo;
import com.fragrance.cfg.FragranceJFinalCfg;
import com.fragrance.model.DeviceMainModel;
import com.fragrance.model.UserDeviceBindModel;
import com.fragrance.model.UserDeviceModel;
import com.fragrance.service.DeviceMainService;
import com.fragrance.service.IotApiService;
import com.fragrance.service.UserDeviceBindService;
import com.fragrance.service.impl.DeviceMainServiceImpl;
import com.fragrance.service.impl.IotApiServiceImpl;
import com.fragrance.service.impl.UserDeviceBindServiceImpl;
import com.fragrance.util.Constants;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Redis;

/**
 * 微信设备操作Controller
 * 
 * @author zhilin
 *
 */
public class WeChatDeviceOprController extends Controller {

	private final static Logger logger = LoggerFactory.getLogger(WeChatDeviceOprController.class);

	private IotApiService iotApiService = new IotApiServiceImpl();

	private DeviceMainService deviceService = new DeviceMainServiceImpl();

	private UserDeviceBindService userDeviceBindService = new UserDeviceBindServiceImpl();

	private final static SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 前缀
	 */
	public final static String PREFIX = "DY";

	/**
	 * 0允许使用，1代表锁机状态
	 */
	public final static String AUTH_0 = "0";

	/**
	 * 0允许使用，1代表锁机状态
	 */
	public final static String AUTH_1 = "1";

	/**
	 * 0代表开机，1代表关机状态
	 */
	public final static String OPEN = "0";

	/**
	 * 0代表开机，1代表关机状态
	 */
	public final static String SHUTDOWN = "1";

	/**
	 * 调档
	 */
	public void setGear() {
		String openid = getPara("openid");
		// 二维码里的数据为imei
		String imei = getPara("imei");
		int gearIndex = getParaToInt("gearIndex") + 1;
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if (gearIndex < 0 && gearIndex > 20) {
			logger.info("gearIndex必须大于0");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		// iotcfg.properties配置的productKey
		String productKey = FragranceJFinalCfg.iotcfgProp.get("carla.iot.productKey");
		if (StringUtils.isEmpty(productKey)) {
			logger.info("请在iotcfg.properties配置carla.iot.productKey");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			// 1、获取香氛机信息t_device_main
			List<DeviceMainModel> deviceMainModels = deviceService.findDevice(imei);
			if (deviceMainModels == null || deviceMainModels.size() == 0) {
				logger.info("根据imei=" + imei + "获取不到设备信息");
				result.put("code", Constants.PARAM_VAILD_CODE);
				result.put("msg", Constants.PARAM_VAILD_MSG);
				renderJson(result);
				return;
			}
			DeviceMainModel deviceMainModel = deviceMainModels.get(0);
			// 判断是否被锁
			String rightStatus = deviceMainModel.getStr("right_status");
			if (StringUtils.isBlank(rightStatus) || "1".equals(rightStatus)) {
				logger.info("设备状态被锁定:" + rightStatus);
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", "设备被锁定，请联系工作人员处理！");
				renderJson(result);
				return;
			}
			// 2、在云端获取机器状态 是否在线
			String deviceName = deviceMainModel.getStr("imei");
			logger.info("productKey=" + productKey + ", deviceName=" + deviceName);
			DeviceInfo deviceInfo = iotApiService.queryDeviceByName(productKey, deviceName);
			if (deviceInfo == null || !Constants.DEV_ONLINE.equals(deviceInfo.getDeviceStatus())) {
				logger.info("设备状态不正确:" + JSON.toJSONString(deviceInfo));
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", Constants.DEV_STATUS_MSG);
				renderJson(result);
				return;
			}

			// 3、在数据库里查询设备是否已经有人使用 表t_user_device
			UserDeviceModel userDeviceModel = deviceService.isUse(imei, openid);
			if (userDeviceModel != null) {
				// 组装发送数据
				String openMsg = PREFIX + "2" + gearIndex;
				logger.info("调档发送的数据：" + openMsg);
				String topic = "/" + productKey + "/" + deviceName + "/get";
				// 该数据发送为异步发送，所以前端需要轮询
				String publishResult = iotApiService.publishMssage(productKey, topic, openMsg);
				if (StringUtils.isNotEmpty(publishResult)) {
					// imei号
					String redisKey = deviceName;
					String msgId = publishResult;
					Redis.use("users").setex(redisKey, 60 * 10, msgId);
					// TODO 可以循环一段时间

					logger.info("上送消息：" + openMsg);
					// 在表t_user_device更新一条记录 说明机器在用
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("wx_open_id", openid);
					data.put("imei", deviceMainModel.getStr("imei"));
					data.put("sim_no", deviceMainModel.getStr("sim_no"));
					data.put("gear", String.valueOf(gearIndex));
					// 更新用户使用设备情况
					boolean flag = deviceService.updateUserDeviceGear(data);

					if (flag) {
						result.put("code", Constants.SUCCESS_CODE);
						result.put("msg", Constants.SUCCESS_MSG);
						renderJson(result);
					} else {
						logger.info("添加用戶使用设备到数据库失败");
						result.put("code", Constants.INSERT_DEV_USE_CODE);
						result.put("msg", Constants.INSERT_DEV_USE_MSG);
						renderJson(result);
					}
				} else {
					logger.info("调档失败");
					result.put("code", Constants.ERROR_CODE);
					result.put("msg", Constants.ERROR_MSG);
					renderJson(result);
				}
			} else {
				logger.info("openid=" + openid + ",setGear没有使用该设备");
				result.put("code", Constants.DEVICE_NOT_USE_CODE);
				result.put("msg", Constants.DEVICE_NOT_USE_MSG);
				renderJson(result);
			}
		} catch (Exception e) {
			logger.error("获取设备信息失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

	/**
	 * 定时
	 */
	public void setTime() {
		String openid = getPara("openid");
		// 二维码里的数据为imei
		String imei = getPara("imei");
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String startTimeIn = getPara("startTime");
		logger.info("----打印从页面传入的时间---startTimeIn={}",startTimeIn);
		String endTimeIn = getPara("endTime");
		String timeType = getPara("timeType");

		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if (StringUtils.isEmpty(startTime)) {
			logger.info("startTime不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if (StringUtils.isEmpty(endTime)) {
			logger.info("endTime不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if (startTime.length() != 5 || !startTime.contains(":")) {
			logger.info("startTime格式不正确：" + startTime);
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (endTime.length() != 5 || !endTime.contains(":")) {
			logger.info("endTime格式不正确：" + endTime);
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		startTime = startTime.replaceAll(":", "");
		endTime = endTime.replaceAll(":", "");

		if (startTime.trim().length() != 4) {
			logger.info("startTime格式不正确");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if (endTime.trim().length() != 4) {
			logger.info("endTime格式不正确");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if (StringUtils.isEmpty(timeType)) {
			logger.info("timeType不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		if ("one".equals(timeType) || "tow".equals(timeType) || "three".equals(timeType)) {
			// iotcfg.properties配置的productKey
			String productKey = FragranceJFinalCfg.iotcfgProp.get("carla.iot.productKey");
			if (StringUtils.isEmpty(productKey)) {
				logger.info("请在iotcfg.properties配置carla.iot.productKey");
				result.put("code", Constants.PARAM_VAILD_CODE);
				result.put("msg", Constants.PARAM_VAILD_MSG);
				renderJson(result);
				return;
			}
			try {
				// 1、获取香氛机信息t_device_main
				List<DeviceMainModel> deviceMainModels = deviceService.findDevice(imei);
				if (deviceMainModels == null || deviceMainModels.size() == 0) {
					logger.info("根据imei=" + imei + "获取不到设备信息");
					result.put("code", Constants.PARAM_VAILD_CODE);
					result.put("msg", Constants.PARAM_VAILD_MSG);
					renderJson(result);
					return;
				}
				DeviceMainModel deviceMainModel = deviceMainModels.get(0);
				// 判断是否被锁
				String rightStatus = deviceMainModel.getStr("right_status");
				if (StringUtils.isBlank(rightStatus) || "1".equals(rightStatus)) {
					logger.info("设备状态被锁定:" + rightStatus);
					result.put("code", Constants.DEV_STATUS_CODE);
					result.put("msg", "设备被锁定，请联系工作人员处理！");
					renderJson(result);
					return;
				}
				// 2、在云端获取机器状态 是否在线
				String deviceName = deviceMainModel.getStr("imei");
				logger.info("productKey=" + productKey + ", deviceName=" + deviceName);
				DeviceInfo deviceInfo = iotApiService.queryDeviceByName(productKey, deviceName);
				if (deviceInfo == null || !Constants.DEV_ONLINE.equals(deviceInfo.getDeviceStatus())) {
					logger.info("设备状态不正确:" + JSON.toJSONString(deviceInfo));
					result.put("code", Constants.DEV_STATUS_CODE);
					result.put("msg", Constants.DEV_STATUS_MSG);
					renderJson(result);
					return;
				}
				// 3、在数据库里查询设备是否已经有人使用 表t_user_device
				UserDeviceModel userDeviceModel = deviceService.isUse(imei, openid);
				Map<String,Object> timeResult = new HashMap<String,Object>();
				if (userDeviceModel != null) {
					// 组装发送数据
					String openMsg = null;
					if (timeType.equals("one")) {
						openMsg = PREFIX + "3A" + startTime + endTime;
						SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
						SimpleDateFormat nowTime = new SimpleDateFormat("yyyy-MM-dd ");
						Date date = new Date();
						if(dateFormat.parse(startTimeIn).before(dateFormat.parse(endTimeIn))){
							timeResult.put("startTime", nowTime.format(date)+startTimeIn);
							timeResult.put("endTime", nowTime.format(date)+endTimeIn);
						}else if(dateFormat.parse(endTimeIn).before(dateFormat.parse(startTimeIn))){
							Calendar calendar = new GregorianCalendar();
							calendar.setTime(date);
							calendar.add(Calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
							date=calendar.getTime(); //这个时间就是日期往后推一天的结果 
							timeResult.put("startTime", nowTime.format(new Date())+startTimeIn);
							timeResult.put("endTime", nowTime.format(date)+endTimeIn);
						}
						timeResult.put("imei", imei);
						timeResult.put("openid", openid);
						timeResult.put("timeType", timeType);
						logger.info("更新的时间数据1：" + timeResult);
						boolean deviceUpdateModel = deviceService.updateWorkTime(timeResult);
					} else if (timeType.equals("tow")) {
						openMsg = PREFIX + "3B" + startTime + endTime;
						SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
						SimpleDateFormat nowTime = new SimpleDateFormat("yyyy-MM-dd ");
						Date date = new Date();
						if(dateFormat.parse(startTimeIn).before(dateFormat.parse(endTimeIn))){
							timeResult.put("startTime", nowTime.format(date)+startTimeIn);
							timeResult.put("endTime", nowTime.format(date)+endTimeIn);
						}else if(dateFormat.parse(endTimeIn).before(dateFormat.parse(startTimeIn))){
							Calendar calendar = new GregorianCalendar();
							calendar.setTime(date);
							calendar.add(Calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
							date=calendar.getTime(); //这个时间就是日期往后推一天的结果 
							timeResult.put("startTime", nowTime.format(new Date())+startTimeIn);
							timeResult.put("endTime", nowTime.format(date)+endTimeIn);
						}
						timeResult.put("imei", imei);
						timeResult.put("openid", openid);
						timeResult.put("timeType", timeType);
						logger.info("更新的时间数据2：" + timeResult);
						boolean deviceUpdateModel = deviceService.updateWorkTime(timeResult);
					} else {
						openMsg = PREFIX + "3C" + startTime + endTime;
						SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
						SimpleDateFormat nowTime = new SimpleDateFormat("yyyy-MM-dd ");
						Date date = new Date();
						if(dateFormat.parse(startTimeIn).before(dateFormat.parse(endTimeIn))){
							timeResult.put("startTime", nowTime.format(date)+startTimeIn);
							timeResult.put("endTime", nowTime.format(date)+endTimeIn);
						}else if(dateFormat.parse(endTimeIn).before(dateFormat.parse(startTimeIn))){
							Calendar calendar = new GregorianCalendar();
							calendar.setTime(date);
							calendar.add(Calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
							date=calendar.getTime(); //这个时间就是日期往后推一天的结果 
							timeResult.put("startTime", nowTime.format(new Date())+startTimeIn);
							timeResult.put("endTime", nowTime.format(date)+endTimeIn);
						}
						timeResult.put("imei", imei);
						timeResult.put("openid", openid);
						timeResult.put("timeType", timeType);
						logger.info("更新的时间数据3：" + timeResult);
						boolean deviceUpdateModel = deviceService.updateWorkTime(timeResult);
					}
					logger.info("定时发送的数据：" + openMsg);
					String topic = "/" + productKey + "/" + deviceName + "/get";
					// 该数据发送为异步发送，所以前端需要轮询
					String publishResult = iotApiService.publishMssage(productKey, topic, openMsg);
					if (StringUtils.isNotEmpty(publishResult)) {
						// imei号
						String redisKey = deviceName;
						String msgId = publishResult;
						Redis.use("users").setex(redisKey, 60 * 10, msgId);
						// TODO 可以循环一段时间

						result.put("code", Constants.SUCCESS_CODE);
						result.put("msg", Constants.SUCCESS_MSG);
						renderJson(result);
					} else {
						logger.info("定时失败");
						result.put("code", Constants.ERROR_CODE);
						result.put("msg", Constants.ERROR_MSG);
						renderJson(result);
						return;
					}
				} else {
					logger.info("openid=" + openid + "，setTime没有使用该设备");
					result.put("code", Constants.DEVICE_NOT_USE_CODE);
					result.put("msg", Constants.DEVICE_NOT_USE_MSG);
					renderJson(result);
					return;
				}
			} catch (Exception e) {
				logger.error("获取设备信息失败", e);
				result.put("code", Constants.ERROR_CODE);
				result.put("msg", Constants.ERROR_MSG);
				renderJson(result);
			}
		} else {
			logger.info("未知的定时类型timeType = " + timeType);
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
		}
	}

	/**
	 * 开始香氛机
	 */
	public void openCarla() {
		String openid = getPara("openid");
		// 二维码里的数据为imei
		String imei = getPara("imei");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}

		// iotcfg.properties配置的productKey
		String productKey = FragranceJFinalCfg.iotcfgProp.get("carla.iot.productKey");
		if (StringUtils.isEmpty(productKey)) {
			logger.info("请在iotcfg.properties配置carla.iot.productKey");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			// 1、获取香氛机信息t_device_main
			List<DeviceMainModel> deviceMainModels = deviceService.findDevice(imei);
			if (deviceMainModels == null || deviceMainModels.size() == 0) {
				logger.info("根据imei=" + imei + "获取不到设备信息");
				result.put("code", Constants.PARAM_VAILD_CODE);
				result.put("msg", Constants.PARAM_VAILD_MSG);
				renderJson(result);
				return;
			}
			DeviceMainModel deviceMainModel = deviceMainModels.get(0);
			// 判断是否被锁
			String rightStatus = deviceMainModel.getStr("right_status");
			if (StringUtils.isBlank(rightStatus) || "1".equals(rightStatus)) {
				logger.info("设备状态被锁定:" + rightStatus);
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", "设备被锁定，请联系工作人员处理！");
				renderJson(result);
				return;
			}
			// 2、在云端获取机器状态 是否在线
			String deviceName = deviceMainModel.getStr("imei");
			logger.info("productKey=" + productKey + ", deviceName=" + deviceName);
			DeviceInfo deviceInfo = iotApiService.queryDeviceByName(productKey, deviceName);
			if (deviceInfo == null || !Constants.DEV_ONLINE.equals(deviceInfo.getDeviceStatus())) {
				logger.info("设备状态不正确:" + JSON.toJSONString(deviceInfo));
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", Constants.DEV_STATUS_MSG);
				renderJson(result);
				return;
			}
			// 3、在数据库里查询设备是否已经有人使用 表t_user_device
			UserDeviceModel userDeviceModel = deviceService.isOpen(imei);
			if (userDeviceModel != null) {
				logger.info("设备已经被占用 userDeviceModel=" + JSON.toJSONString(userDeviceModel));
				result.put("code", Constants.DEVICE_IS_OPEN);
				result.put("msg", Constants.DEVICE_IS_MSG);
				renderJson(result);
				return;
			}
			// 组装发送数据
			String openMsg = PREFIX + "11";

			String topic = "/" + productKey + "/" + deviceName + "/get";
			// 该数据发送为异步发送，所以前端需要轮询
			String publishResult = iotApiService.publishMssage(productKey, topic, openMsg);
			if (StringUtils.isNotEmpty(publishResult)) {
				// imei号
				String redisKey = deviceName;
				String msgId = publishResult;
				Redis.use("users").setex(redisKey, 60 * 10, msgId);
				// TODO 可以循环一段时间

				logger.info("上送消息：" + openMsg);
				// 在表t_user_device更新一条记录 说明机器在用
				Map<String, String> data = new HashMap<String, String>();
				data.put("wx_open_id", openid);
				data.put("imei", deviceMainModel.getStr("imei"));
				data.put("sim_no", deviceMainModel.getStr("sim_no"));
				// 更新设备再使用
				data.put("device_status", String.valueOf(0));
				// 更新用户使用设备情况
				boolean flag = deviceService.addUserDevice(data);
				if (!flag) {
					logger.info("添加用戶使用设备到数据库失败");
					result.put("code", Constants.INSERT_DEV_USE_CODE);
					result.put("msg", Constants.INSERT_DEV_USE_MSG);
					renderJson(result);
					return;
				}
				// 关机状态
				Integer oldDeviceStatus = 1;
				// 开机状态
				Integer newDeviceStatus = 0;
				flag = deviceService.updateStatus(newDeviceStatus, imei, oldDeviceStatus);

				if (flag) {
					logger.info("开机成功");
					String value = "A";
					Redis.use("users").setex(imei,24 * 60 * 60, value);
					result.put("code", Constants.SUCCESS_CODE);
					result.put("msg", Constants.SUCCESS_MSG);
					renderJson(result);
				} else {
					logger.info("更新t_device_main表设备使用状态失败");
					result.put("code", Constants.INSERT_DEV_USE_CODE);
					result.put("msg", Constants.INSERT_DEV_USE_MSG);
					renderJson(result);
				}
			} else {
				logger.info("开机失败");
				result.put("code", Constants.ERROR_CODE);
				result.put("msg", Constants.ERROR_MSG);
				renderJson(result);
			}
		} catch (Exception e) {
			logger.error("获取设备信息失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

	/**
	 * 关闭香氛机
	 */
	public void closeCarla() {
		String openid = getPara("openid");
		// 二维码里的数据为imei
		String imei = getPara("imei");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			UserDeviceModel userDeviceModel = deviceService.findUserDevice(imei, openid, "0");
			// 1、判断该用户是否使用设备
			if (userDeviceModel == null) {
				logger.info("获取不到openid=" + openid + "使用imei=" + imei + "的记录");
				result.put("code", Constants.DEVICE_NOT_USE_CODE);
				result.put("msg", Constants.DEVICE_NOT_USE_MSG);
				renderJson(result);
				return;
			}
			// 2、获取香氛机信息t_device_main
			List<DeviceMainModel> deviceMainModels = deviceService.findDevice(imei);
			if (deviceMainModels == null || deviceMainModels.size() == 0) {
				logger.info("根据imei=" + imei + "获取不到设备信息");
				result.put("code", Constants.PARAM_VAILD_CODE);
				result.put("msg", Constants.PARAM_VAILD_MSG);
				renderJson(result);
				return;
			}
			// iotcfg.properties配置的productKey
			String productKey = IotClient.getValue("carla.iot.productKey");
			if (StringUtils.isEmpty(productKey)) {
				logger.info("productKey请在iotcfg.properties配置");
				result.put("code", Constants.PARAM_VAILD_CODE);
				result.put("msg", Constants.PARAM_VAILD_MSG);
				renderJson(result);
				return;
			}
			DeviceMainModel deviceMainModel = deviceMainModels.get(0);

			// 判断是否被锁
			String rightStatus = deviceMainModel.getStr("right_status");
			if (StringUtils.isBlank(rightStatus) || "1".equals(rightStatus)) {
				logger.info("设备状态被锁定:" + rightStatus);
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", "设备被锁定，请联系工作人员处理！");
				renderJson(result);
				return;
			}

			// 判断是否已被关机
			String deviceStatus = deviceMainModel.getStr("device_status");
			if (StringUtils.isBlank(deviceStatus) || "1".equals(deviceStatus)) {
				logger.info("设备状态已关机:" + rightStatus);
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", "设备已关机");
				renderJson(result);
				return;
			}

			// 3、在云端获取机器状态是否在线
			String deviceName = deviceMainModel.getStr("imei");
			logger.info("productKey=" + productKey + ", deviceName=" + deviceName);
			DeviceInfo deviceInfo = iotApiService.queryDeviceByName(productKey, deviceName);
			if (deviceInfo != null && Constants.DEV_ONLINE.equals(deviceInfo.getDeviceStatus())) {
				// 进行远程关机操作
				logger.info("进行关机操作:" + JSON.toJSONString(deviceInfo));
				// 组装发送数据
				String openMsg = PREFIX + "10";
				String topic = "/" + productKey + "/" + deviceName + "/get";
				// 该数据发送为异步发送，所以前端需要轮询
				String msgId = iotApiService.publishMssage(productKey, topic, openMsg);
				// imei号
				String redisKey = deviceName;
				Redis.use("users").setex(redisKey, 60 * 10, msgId);
				// TODO 可以循环一段时间

				if (StringUtils.isEmpty(msgId)) {
					logger.info("--关机失败1--");
					result.put("code", Constants.ERROR_CODE);
					result.put("msg", Constants.ERROR_MSG);
					renderJson(result);
					return;
				} else {
					logger.info("上送消息：" + openMsg);
					logger.info("--关机成功1--");
				}
			}
			// 修改数据库的device_status状态为关机
			Map<String, String> data = new HashMap<String, String>();
			data.put("wx_open_id", openid);
			data.put("imei", deviceMainModel.getStr("imei"));
			data.put("sim_no", deviceMainModel.getStr("sim_no"));
			// 不再使用设备
			data.put("device_status", String.valueOf(1));
			Date date = new Date();
			data.put("close_time", FORMAT.format(date));
			boolean flag = deviceService.updateUserDevice(data);
			if (!flag) {
				logger.info("--关机失败,更新用户使用设备失败--");
				result.put("code", Constants.ERROR_CODE);
				result.put("msg", Constants.ERROR_MSG);
				renderJson(result);
				return;
			}
			// 开机
			Integer oldDeviceStatus = 0;
			// 关机
			Integer newDeviceStatus = 1;
			flag = deviceService.updateStatus(newDeviceStatus, imei, oldDeviceStatus);
			if (flag) {
				logger.info("--关机成功2--");
				Redis.use("users").del(imei);
				result.put("code", Constants.SUCCESS_CODE);
				result.put("msg", Constants.SUCCESS_MSG);
				renderJson(result);
			} else {
				logger.info("--关机失败2--");
				result.put("code", Constants.ERROR_CODE);
				result.put("msg", Constants.ERROR_MSG);
				renderJson(result);
			}
		} catch (Exception e) {
			logger.error("关机失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

	/**
	 * 检查设备是否绑定并开机
	 */
	public void checkBindAndOpen() {
		logger.info("--- begin checkBindAndOpen ---");
		String openid = getPara("openid");
		// 二维码里的数据为imei
		String imei = getPara("imei");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("imei", imei);
			params.put("openid", openid);
			logger.info("---- 打印出传入的参数值   params:{}", params);
			result = deviceService.checkBindAndOpen(params);
			renderJson(result);
		} catch (Exception e) {
			logger.error("error checkBindAndOpen 查询设备信息失败", e);
			result.put("code", "100010");
			result.put("msg", "检查设备失败");
			renderJson(result);
		}
	}

	/**
	 * 绑定香氛机
	 */
	public void bindCarla() {
		// 获取微信的openID
		String openid = getPara("openid");
		// 二维码里的数据为imei
		String imei = getPara("imei");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			// 1、获取香氛机信息t_device_main
			List<DeviceMainModel> deviceMainModels = deviceService.findDevice(imei);
			if (deviceMainModels == null || deviceMainModels.size() == 0) {
				logger.info("根据imei=" + imei + "获取不到设备信息");
				result.put("code", Constants.PARAM_VAILD_CODE);
				result.put("msg", Constants.PARAM_VAILD_MSG);
				renderJson(result);
				return;
			}
			
			DeviceMainModel deviceMainModel = deviceMainModels.get(0);
			
			// 判断是否被锁
			String rightStatus = deviceMainModel.getStr("right_status");
			if (StringUtils.isBlank(rightStatus) || "1".equals(rightStatus)) {
				logger.info("设备状态被锁定:" + rightStatus);
				result.put("code", Constants.DEV_STATUS_CODE);
				result.put("msg", "设备被锁定，请联系工作人员处理！");
				renderJson(result);
				return;
			}
			
			//获取remark值，1代表改设备可以帮定多个用户，2代表该设备智能绑定一个用户
			String remark1 = deviceMainModel.getStr("remark1");
			logger.info("设备多用户绑定值:remark1:{}" + remark1);
			// 判断设备是否已经被绑定,通过remark值可以判断是否可以进行多台绑定
			List<UserDeviceBindModel> userDeviceBindModels = userDeviceBindService.findBindDevice(imei);
			logger.info("设备绑定值:userDeviceBindModels:{}" , userDeviceBindModels.toString());
			if(remark1.equals("2")){
				if (userDeviceBindModels != null && userDeviceBindModels.size() >= 1) {
					logger.info("该设备已经被绑定imei = " + imei);
					result.put("code", Constants.PARAM_VAILD_CODE);
					result.put("msg", "该设备已经被绑定，请更换设备");
					renderJson(result);
					return;
				}
			}else if(remark1.equals("1")){
				if (userDeviceBindModels != null && userDeviceBindModels.size() > 5) {
					logger.info("该设备已经被绑定imei = " + imei);
					result.put("code", Constants.PARAM_VAILD_CODE);
					result.put("msg", "该设备已经被绑定，请更换设备");
					renderJson(result);
					return;
				}
			}
			
			
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("imei", imei);
			data.put("openid", openid);
			boolean flag = userDeviceBindService.bindCarlaToUser(data);
			if (flag) {
				logger.info("绑定设备成功成功");
				result.put("code", Constants.SUCCESS_CODE);
				result.put("msg", Constants.SUCCESS_MSG);
				renderJson(result);
			} else {
				logger.info("添加用戶绑定设备到数据库失败");
				result.put("code", Constants.BIND_ERROR_CODE);
				result.put("msg", Constants.BIND_ERROR_MSG);
				renderJson(result);
			}
		} catch (Exception e) {
			logger.error("获取设备信息失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

	/**
	 * 解绑香氛机
	 */
	public void unBindCarla() {
		// 获取微信的openID
		String openid = getPara("openid");
		// 传入的imei
		String imei = getPara("imei");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("imei", imei);
			data.put("openid", openid);
			// 判断该微信是否绑定了该设备
			UserDeviceBindModel userDeviceBindModel = userDeviceBindService.findBindDeviceInfo(data);
			if (userDeviceBindModel == null) {
				logger.info("该设备未绑定到此微信");
				result.put("code", Constants.DEVICE_EXIST_CODE);
				result.put("msg", Constants.DEVICE_EXIST_MSG);
				renderJson(result);
				return;
			}
			//先判断是否已经开机，若开机，提示关机后再解绑
			UserDeviceModel userDeviceModel = deviceService.isBindOpenOpen(data);
			if (userDeviceModel != null) {
				logger.info("设备已经开机 userDeviceModel=" + JSON.toJSONString(userDeviceModel));
				result.put("code", "000011");
				result.put("msg", "设备正在使用中，请关机后再进行解绑");
				renderJson(result);
				return;
			}
			
			// 解锁设备
			Boolean flag = userDeviceBindService.unBindCarla(data);
			if (flag) {
				logger.info("解绑设备成功");
				result.put("code", Constants.SUCCESS_CODE);
				result.put("msg", Constants.SUCCESS_MSG);
				renderJson(result);
			} else {
				logger.info("用戶解绑设备到数据库失败");
				result.put("code", Constants.UNBIND_ERROR_CODE);
				result.put("msg", Constants.UNBIND_ERROR_MSG);
				renderJson(result);
			}
		} catch (Exception e) {
			logger.error("获取绑定设备信息失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

	/**
	 * 点击操作设备，获取设备的定时信息档位信息
	 * 
	 */
	public void getDeviceWorkInfo() {
		logger.info("--- begin WeChatDeviceOprController.getDeviceWorkInfo ---");
		String openid = getPara("openid");
		// 点击操作传入的imei
		String imei = getPara("imei");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		if (StringUtils.isEmpty(imei)) {
			logger.info("imei不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("imei", imei);
			data.put("openid", openid);
			// 先判断该机器是否在使用中
			UserDeviceModel userDeviceModel = deviceService.isOpen(imei);
			if (userDeviceModel != null) {
				logger.info("设备已经在使用中 imei=" + imei);
				// 获取开机的信息
				UserDeviceModel deviceOpenInfo = deviceService.deviceOpenInfo(data);
				logger.info("-- 根据设备信息查询到的值-- deviceOpenInfo{}",deviceOpenInfo);
				if (deviceOpenInfo != null) {
					String time1 = deviceOpenInfo.getStr("work_start_time1"); // 开机时间1
					String time2 = deviceOpenInfo.getStr("work_close_time1"); // 关机时间1
					String time3 = deviceOpenInfo.getStr("work_start_time2"); // 开机时间2
					String time4 = deviceOpenInfo.getStr("work_close_time2"); // 关机时间2
					String time5 = deviceOpenInfo.getStr("work_start_time3"); // 开机时间3
					String time6 = deviceOpenInfo.getStr("work_close_time3"); // 关机时间3
					String work_start_time1;
					String work_close_time1;
					String work_start_time2;
					String work_close_time2;
					String work_start_time3;
					String work_close_time3;
					if(time1 == null || time2 == null){
						work_start_time1 = "00:00"; // 开机时间1
						work_close_time1 = "00:00"; // 关机时间1
					}else{
						work_start_time1 = time1.substring(11, 16); // 开机时间1
						logger.info("-- 截取的时间 -- work_start_time1{}",work_start_time1);
						work_close_time1 = time2.substring(11, 16); // 关机时间1
					}
					
					if(time3 == null || time4 == null){
						work_start_time2 = "00:00"; // 开机时间1
						work_close_time2 = "00:00"; // 关机时间1
					}else{
						work_start_time2 = time3.substring(11, 16); // 开机时间1
						logger.info("-- 截取的时间 -- work_start_time2{}",work_start_time2);
						work_close_time2 = time4.substring(11, 16); // 关机时间1
					}
					
					if(time5 == null || time6 == null){
						work_start_time3 = "00:00"; // 开机时间1
						work_close_time3 = "00:00"; // 关机时间1
					}else{
						work_start_time3 = time5.substring(11, 16); // 开机时间1
						logger.info("-- 截取的时间 -- work_start_time1{}",work_start_time3);
						work_close_time3 = time6.substring(11, 16); // 关机时间1
					}
					
					int gear ;
					String gearGet  = deviceOpenInfo.getStr("gear");
					if( gearGet == null ){
						gear = 1;
					}else{
						gear = Integer.parseInt(deviceOpenInfo.getStr("gear"));  //档位
					}
					Map<String,Object> deviceInfoMap = new HashMap<String,Object>();
					
					deviceInfoMap.put("work_start_time1", work_start_time1);
					deviceInfoMap.put("work_close_time1", work_close_time1);
					deviceInfoMap.put("work_start_time2", work_start_time2);
					deviceInfoMap.put("work_close_time2", work_close_time2);
					deviceInfoMap.put("work_start_time3", work_start_time3);
					deviceInfoMap.put("work_close_time3", work_close_time3);
					deviceInfoMap.put("gear", gear-1);
					
					result.put("info", deviceInfoMap);
					result.put("code", Constants.SUCCESS_CODE);
					result.put("msg", Constants.SUCCESS_MSG);
					renderJson(result);
				}else{
					logger.info("获取开机的信息失败imei=" + imei);
					result.put("code", Constants.ERROR_CODE);
					result.put("msg", Constants.ERROR_MSG);
					renderJson(result);
				}
			} else {
				logger.info("设备没在使用imei=" + imei);
				Map<String, Object> deviceOpenInfo = new HashMap<String, Object>();
				int gear = 0;// 档位
				String work_start_time1 = "00:00"; // 开机时间1
				String work_close_time1 = "00:00"; // 关机时间1
				String work_start_time2 = "00:00"; // 开机时间2
				String work_close_time2 = "00:00"; // 关机时间2
				String work_start_time3 = "00:00"; // 开机时间3
				String work_close_time3 = "00:00"; // 关机时间3

				deviceOpenInfo.put("gear", gear);
				deviceOpenInfo.put("work_start_time1", work_start_time1);
				deviceOpenInfo.put("work_close_time1", work_close_time1);
				deviceOpenInfo.put("work_start_time2", work_start_time2);
				deviceOpenInfo.put("work_close_time2", work_close_time2);
				deviceOpenInfo.put("work_start_time3", work_start_time3);
				deviceOpenInfo.put("work_close_time3", work_close_time3);

				result.put("info", deviceOpenInfo);
				result.put("code", Constants.SUCCESS_CODE);
				result.put("msg", Constants.SUCCESS_MSG);
				renderJson(result);
			}
		} catch (Exception e) {
			logger.error("获取设备的定时信息档位信息失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

	/**
	 * 获取我的设备列表
	 */
	public void getMyDeviceList() {
		logger.info("--- begin WeChatDeviceOprController.getMyDeviceList ---");
		String openid = getPara("openid");
		Map<String, Object> result = new HashMap<String, Object>();
		if (StringUtils.isEmpty(openid)) {
			logger.info("openid不能为空");
			result.put("code", Constants.PARAM_VAILD_CODE);
			result.put("msg", Constants.PARAM_VAILD_MSG);
			renderJson(result);
			return;
		}
		try {
			// 获取我的设备列表
			List<Map> userDeviceOnlineList = userDeviceBindService.getMyDeviceList(openid);
			result.put("list", userDeviceOnlineList);
			result.put("code", Constants.SUCCESS_CODE);
			result.put("msg", Constants.SUCCESS_MSG);
			renderJson(result);
		} catch (Exception e) {
			logger.error("获取设备列表失败", e);
			result.put("code", Constants.ERROR_CODE);
			result.put("msg", Constants.ERROR_MSG);
			renderJson(result);
		}
	}

}
